package messages;

/**
 * This class creates a conversion between the C-String and Java String classes
 * 
 * @author Ian
 *
 */
public class CString {
    
    private String str;
    
    /**
     * parses out a CString from the given data array
     * 
     * @param data
     * @param startIndex
     */
    public CString(byte[] data, int startIndex)
    {
        int len = 0;
        
        while (data[startIndex + len] != 0)
        {
            len++;
        }
        
        str = new String(data, startIndex, len);
    }
    
    /**
     * Creates a CString object from the given String
     * 
     * @param s
     */
    public CString(String s)
    {
        this.str = s;
    }
    
    @Override
    /**
     * Returns the Java String version of this String
     */
    public String toString()
    {
        return str;
    }
    
    /**
     * Returns the length of this C String
     * 
     * @return
     */
    public int getLength()
    {
        return str.length() + 1;
    }
    
    /**
     * appends this CString to the given ByteList.
     * 
     * @param list
     */
    public void appendToByteList(ByteList list)
    {
        for (int i = 0;i < str.length();i++)
        {
            list.addByte((byte) str.charAt(i));
        }
        
        list.addByte((byte) 0);
    }
    
}
